package com.hhit.zhgd.service.impl

import cn.afterturn.easypoi.excel.ExcelImportUtil
import cn.afterturn.easypoi.excel.entity.ImportParams
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult
import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.collection.CollUtil
import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.metadata.IPage
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.hhit.zhgd.component.FileProperties
import com.hhit.zhgd.dao.ZhgdHighlightGreenConstructionMapper
import com.hhit.zhgd.domain.dto.BaskStageHighlightGreenConstructionDTO
import com.hhit.zhgd.domain.dto.GreenConstructionScoreRateDTO
import com.hhit.zhgd.domain.dto.HighlightSituationDTO
import com.hhit.zhgd.domain.entity.ZhgdHighlightGreenConstruction
import com.hhit.zhgd.domain.excelimport.HighlightGreenConstructionImportParam
import com.hhit.zhgd.domain.response.BaseResp
import com.hhit.zhgd.service.ZhgdHighlightGreenConstructionService
import jakarta.annotation.Resource
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.multipart.MultipartFile
import java.math.BigDecimal
import java.util.stream.Collectors

@Service("zhgdHighlightGreenConstructionService")
class ZhgdHighlightGreenConstructionServiceImpl : ZhgdHighlightGreenConstructionService,
    ServiceImpl<ZhgdHighlightGreenConstructionMapper, ZhgdHighlightGreenConstruction>() {

    private val HIGHLIGHT_MAJOR = "业主,设计,土建施工,电气施工,监理"

    @Resource
    private val fileProperties: FileProperties? = null

    @Transactional(rollbackFor = [Exception::class])
    override fun importHighlightGreenConstruction(multipartFile: MultipartFile?): BaseResp<Any?>? {
        this.remove(QueryWrapper())
        val params = ImportParams()
        // 表头设置为1行
        params.headRows = 1
        val result: ExcelImportResult<HighlightGreenConstructionImportParam?> =
            ExcelImportUtil.importExcelMore<HighlightGreenConstructionImportParam>(
                multipartFile!!.inputStream,
                HighlightGreenConstructionImportParam::class.java, params
            )
        if (CollUtil.isNotEmpty(result.failList)) {
            for (highlightGreenConstructionImportParam in result.failList) {
                val msg =
                    "第" + ((highlightGreenConstructionImportParam?.getRowNum()
                        ?: 0) + 1) + "行的错误是：" + highlightGreenConstructionImportParam?.errorMsg
                return BaseResp.fail("导入失败:$msg")
            }
        }
        val zhgdHighlightGreenConstructions: MutableList<ZhgdHighlightGreenConstruction> = CollUtil.newArrayList()
        for (highlightGreenConstructionImportParam in result.getList()) {
            val zhgdHighlightGreenConstruction = ZhgdHighlightGreenConstruction()
            BeanUtil.copyProperties(highlightGreenConstructionImportParam, zhgdHighlightGreenConstruction)
            if (StrUtil.isNotBlank(highlightGreenConstructionImportParam?.planningPhoto)) {
                zhgdHighlightGreenConstruction.planningPhoto =
                    highlightGreenConstructionImportParam?.planningPhoto
                        ?.replace(fileProperties?.parentPath ?: "", "/images")
            }
            if (StrUtil.isNotBlank(highlightGreenConstructionImportParam?.actualFinishedPhoto)) {
                zhgdHighlightGreenConstruction.actualFinishedPhoto =
                    highlightGreenConstructionImportParam?.actualFinishedPhoto
                        ?.replace(fileProperties?.parentPath ?: "", "/images")
            }
            zhgdHighlightGreenConstructions.add(zhgdHighlightGreenConstruction)
        }
        val saveBatchRes = this.saveBatch(zhgdHighlightGreenConstructions)
        return if (saveBatchRes) {
            BaseResp.success()
        } else {
            BaseResp.fail("导入亮点、绿色建造数据失败!")
        }
    }

    override fun getHighlightSituation(): List<HighlightSituationDTO?>? {
        val highLightMajors = HIGHLIGHT_MAJOR.split(",".toRegex()).dropLastWhile { it.isEmpty() }
            .toTypedArray()
        val highlightSituationDTOS: MutableList<HighlightSituationDTO> = CollUtil.newArrayList()
        for (highLightMajor in highLightMajors) {
            val queryWrapper = QueryWrapper<ZhgdHighlightGreenConstruction>().eq("affiliated_unit", highLightMajor)
            val zhgdHighlightGreenConstructions = this.list(queryWrapper)
            val highlightSituationDTO = HighlightSituationDTO()
            highlightSituationDTO.affiliatedUnit = highLightMajor
            //阳光岛需求展示数量
//            highlightSituationDTO.setHighlightScore(zhgdHighlightGreenConstructions.size() + "");
            if (CollUtil.isEmpty(zhgdHighlightGreenConstructions)) {
                highlightSituationDTO.highlightScore = BigDecimal.ZERO.toString() + "%"
            } else {
                // 看下有完成时间的数量
                // 计算公式就是 有完成时间的数量/该专业的总数
                val total = zhgdHighlightGreenConstructions.size
                val filterCollect =
                    zhgdHighlightGreenConstructions.stream().filter { t: ZhgdHighlightGreenConstruction? ->
                        StrUtil.isNotBlank(
                            t!!.completeTime
                        )
                    }.collect(Collectors.toList())
                highlightSituationDTO.highlightScore =
                    BigDecimal.valueOf(java.lang.Double.valueOf(filterCollect.size.toDouble()))
                        .multiply(BigDecimal.valueOf(java.lang.Double.valueOf(total.toDouble()))).setScale(0)
                        .toString() + "%"
            }
            highlightSituationDTOS.add(highlightSituationDTO)
        }
        return highlightSituationDTOS
    }

    override fun getGreenConstructionScoreRate(): List<GreenConstructionScoreRateDTO?>? {
        TODO("Not yet implemented")
    }

    override fun highlightGreenConstructionAdd(baskStageHighlightGreenConstructionDTO: BaskStageHighlightGreenConstructionDTO?): BaseResp<Any?>? {
        TODO("Not yet implemented")
    }

    override fun highlightGreenConstructionEdit(baskStageHighlightGreenConstructionDTO: BaskStageHighlightGreenConstructionDTO?): BaseResp<Any?>? {
        TODO("Not yet implemented")
    }

    override fun getHighlightGreenConstructionPageInfo(
        keyWord: String?,
        page: Int,
        size: Int
    ): IPage<BaskStageHighlightGreenConstructionDTO?>? {
        TODO("Not yet implemented")
    }

    override fun highlightGreenConstructionDel(id: Int?): BaseResp<Any?>? {
        TODO("Not yet implemented")
    }

}